package cn.mujiankeji.mbrowser.界面.小窗页

import android.Manifest
import android.content.pm.PackageManager
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import cn.mujiankeji.mbrowser.界面.框架.小窗视图.小窗状态
import com.google.zxing.*
import com.google.zxing.common.HybridBinarizer
import java.util.concurrent.Executors

class 扫码窗口状态(val 结果回调: (String) -> Unit) : 小窗状态() {
    var 扫描中 by mutableStateOf(true)
    var 错误信息 by mutableStateOf<String?>(null)
    var 需要请求权限 by mutableStateOf(true)

    fun 处理扫描结果(结果: String) {
        扫描中 = false
        结果回调(结果)
        关闭()
    }

    fun 设置错误(信息: String) {
        错误信息 = 信息
    }

    fun 关闭() {
        super.销毁小窗()
    }
}

@Composable
fun 扫码窗口实现(state: 扫码窗口状态) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val cameraExecutor = remember { Executors.newSingleThreadExecutor() }

    // 检查相机权限
    val 相机权限状态 = remember {
        mutableStateOf(
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        )
    }

    // 请求相机权限
    val 权限请求启动器 = rememberLauncherForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { 已授权 ->
        if (已授权) {
            相机权限状态.value = true
            state.需要请求权限 = false
        } else {
            state.设置错误("需要相机权限才能扫描二维码")
        }
    }

    // 请求权限（如果需要）
    LaunchedEffect(state.需要请求权限) {
        if (state.需要请求权限 && !相机权限状态.value) {
            权限请求启动器.launch(Manifest.permission.CAMERA)
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.7f))
            .padding(16.dp),
        contentAlignment = Alignment.Center
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.8f),
            shape = RoundedCornerShape(16.dp)
        ) {
            Box(modifier = Modifier.fillMaxSize()) {
                // 标题和关闭按钮
                Column(modifier = Modifier.fillMaxSize()) {
                    // 标题栏
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(8.dp)
                    ) {
                        Text(
                            text = "扫描二维码",
                            style = MaterialTheme.typography.titleLarge,
                            modifier = Modifier.align(Alignment.Center)
                        )
                        IconButton(
                            onClick = { state.关闭() },
                            modifier = Modifier.align(Alignment.CenterEnd)
                        ) {
                            Icon(Icons.Default.Close, contentDescription = "关闭")
                        }
                    }

                    // 相机预览或错误信息
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .fillMaxWidth()
                            .padding(16.dp)
                    ) {
                        when {
                            state.错误信息 != null -> {
                                // 显示错误信息
                                Column(
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(16.dp),
                                    verticalArrangement = Arrangement.Center,
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = state.错误信息 ?: "发生未知错误",
                                        textAlign = TextAlign.Center,
                                        color = MaterialTheme.colorScheme.error
                                    )
                                    Spacer(modifier = Modifier.height(16.dp))
                                    Button(onClick = { state.关闭() }) {
                                        Text("关闭")
                                    }
                                }
                            }
                            !相机权限状态.value -> {
                                // 请求相机权限
                                Column(
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .padding(16.dp),
                                    verticalArrangement = Arrangement.Center,
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = "需要相机权限才能扫描二维码",
                                        textAlign = TextAlign.Center
                                    )
                                    Spacer(modifier = Modifier.height(16.dp))
                                    Button(onClick = { 权限请求启动器.launch(Manifest.permission.CAMERA) }) {
                                        Text("授权相机")
                                    }
                                }
                            }
                            else -> {
                                // 相机预览和扫描
                                Box(modifier = Modifier.fillMaxSize()) {
                                    // 相机预览
                                    AndroidView(
                                        factory = { ctx ->
                                            PreviewView(ctx).apply {
                                                implementationMode = PreviewView.ImplementationMode.COMPATIBLE
                                            }
                                        },
                                        modifier = Modifier.fillMaxSize(),
                                        update = { previewView ->
                                            val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
                                            cameraProviderFuture.addListener({
                                                try {
                                                    val cameraProvider = cameraProviderFuture.get()

                                                    // 设置预览
                                                    val preview = Preview.Builder().build()
                                                    preview.setSurfaceProvider(previewView.surfaceProvider)

                                                    // 设置图像分析器
                                                    val imageAnalysis = ImageAnalysis.Builder()
                                                        .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                                                        .build()

                                                    imageAnalysis.setAnalyzer(cameraExecutor, QRCodeAnalyzer { result ->
                                                        if (state.扫描中) {
                                                            state.处理扫描结果(result)
                                                        }
                                                    })

                                                    // 选择后置相机
                                                    val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

                                                    // 解绑所有用例，绑定新的用例
                                                    cameraProvider.unbindAll()
                                                    cameraProvider.bindToLifecycle(
                                                        lifecycleOwner,
                                                        cameraSelector,
                                                        preview,
                                                        imageAnalysis
                                                    )

                                                } catch (e: Exception) {
                                                    Log.e("扫码窗口", "相机初始化失败", e)
                                                    state.设置错误("相机初始化失败: ${e.message}")
                                                }
                                            }, ContextCompat.getMainExecutor(context))
                                        }
                                    )

                                    // 扫描区域指示器
                                    Box(
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .padding(32.dp)
                                    ) {
                                        // 这里可以添加自定义的扫描区域指示器，如四角框线等
                                    }
                                }
                            }
                        }
                    }

                    // 底部提示
                    Text(
                        text = "将二维码/条形码放入框内自动扫描",
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 16.dp)
                    )
                }
            }
        }
    }

    // 清理资源
    DisposableEffect(Unit) {
        onDispose {
            cameraExecutor.shutdown()
        }
    }
}

// 二维码分析器
private class QRCodeAnalyzer(private val onQRCodeScanned: (String) -> Unit) : ImageAnalysis.Analyzer {
    private val reader = MultiFormatReader().apply {
        val formatMap = mapOf(
            DecodeHintType.POSSIBLE_FORMATS to arrayListOf(
                BarcodeFormat.QR_CODE,
                BarcodeFormat.CODE_39,
                BarcodeFormat.CODE_93,
                BarcodeFormat.CODE_128,
                BarcodeFormat.EAN_13,
                BarcodeFormat.EAN_8,
                BarcodeFormat.UPC_A,
                BarcodeFormat.UPC_E
            )
        )
        setHints(formatMap)
    }

    @androidx.camera.core.ExperimentalGetImage
    override fun analyze(imageProxy: ImageProxy) {
        val mediaImage = imageProxy.image
        if (mediaImage != null) {
            val buffer = mediaImage.planes[0].buffer
            val bytes = ByteArray(buffer.remaining())
            buffer.get(bytes)

            val width = mediaImage.width
            val height = mediaImage.height

            // 从图像创建PlanarYUVLuminanceSource
            val source = PlanarYUVLuminanceSource(
                bytes,
                width,
                height,
                0,
                0,
                width,
                height,
                false
            )

            val binaryBitmap = BinaryBitmap(HybridBinarizer(source))

            try {
                val result = reader.decode(binaryBitmap)
                onQRCodeScanned(result.text)
            } catch (e: Exception) {
                // 解码失败，继续分析下一帧
            } finally {
                imageProxy.close()
            }
        } else {
            imageProxy.close()
        }
    }
}

// PlanarYUVLuminanceSource类，用于处理YUV格式的图像数据
private class PlanarYUVLuminanceSource(
    private val yuvData: ByteArray,
    private val dataWidth: Int,
    private val dataHeight: Int,
    private val left: Int,
    private val top: Int,
    private val width: Int,
    private val height: Int,
    private val reverseHorizontal: Boolean
) : LuminanceSource(width, height) {

    override fun getRow(y: Int, row: ByteArray?): ByteArray {
        if (y < 0 || y >= height) {
            throw IllegalArgumentException("Requested row is outside the image: $y")
        }
        val width = width
        val row = row ?: ByteArray(width)
        val offset = (y + top) * dataWidth + left
        System.arraycopy(yuvData, offset, row, 0, width)
        if (reverseHorizontal) {
            var x = 0
            var limit = width / 2
            while (x < limit) {
                val temp = row[x]
                row[x] = row[width - x - 1]
                row[width - x - 1] = temp
                x++
            }
        }
        return row
    }

    override fun getMatrix(): ByteArray {
        val width = width
        val height = height
        if (width == dataWidth && height == dataHeight) {
            return yuvData
        }
        val area = width * height
        val matrix = ByteArray(area)
        var inputOffset = top * dataWidth + left
        if (width == dataWidth) {
            System.arraycopy(yuvData, inputOffset, matrix, 0, area)
            return matrix
        }
        for (y in 0 until height) {
            val outputOffset = y * width
            System.arraycopy(yuvData, inputOffset, matrix, outputOffset, width)
            inputOffset += dataWidth
        }
        return matrix
    }
}